<template>
  <el-card class="w-full pt-[5px]">
    <div class="font-bold block-title">
      <!-- <el-icon class="mr-[5px]"><Plus /></el-icon> -->
      <el-icon class="mr-[5px] text-[#409EFF] align-middle" :size="26">
        <Tickets />
      </el-icon>自定义报表
    </div>
    <el-divider class="mt-2" />
    <!-- <div class="line-view"></div> -->
    <el-form :model="searchForm" class="mt-[20px]" label-width="96px">
      <el-row :gutter="20">
        <el-col :span="24">
          <!-- <el-form-item label="行表头：">
            <el-cascader ref="rowRef" :options="rowOptions" :props=" rowProps" :show-all-levels="false" @change="rowChange" />
          </el-form-item> -->
          <el-form-item label="行表头：" class="relative justify-start se-box">
            <div class="cursor-pointer text-[#aeb1b0] pl-2.5 w-[80px] absolute left-0 top-0">请选择</div>
            <el-cascader ref="rowRef" :options="rowOptions" :props="rowProps" :show-all-levels="false" placeholder=" "
              v-model="rowVal" @change="rowChange" class="w-[214px] h-[30px] bg-transparent" />
            <div v-if="rowSelected.length > 0" class="h-auto flex flex-1 flex-wrap">
              <span class="bg-gray-400 mx-2 mb-2 rounded-md h-[32px] text-white">
                <span class="px-2">{{ rowSelected[0].label || '' }}</span>
              </span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="rowSelected.length > 0">
          <el-form-item label="列表头：" class="mb-[0px] relative justify-start se-box">
            <div class="cursor-pointer text-[#aeb1b0] pl-2.5 w-[80px] absolute left-0 top-0">请选择</div>
            <el-cascader :options="colOptions" :props="colProps" ref="colRef" :show-all-levels="false" placeholder=" "
              v-model="colVal" @change="colChange" class="w-[214px] h-[30px] bg-transparent" />
            <div class="h-auto flex flex-1 flex-wrap">
              <template v-for="(item, index) in colSelected" :key="index">
                <template v-if="item.children.length == 0">
                  <!-- 渲染最后一层 -->
                  <span :key="index" class="bg-gray-400 mx-2 mb-2 rounded-md h-[32px] text-white">
                    <span class="px-2">{{ item.label }}</span>
                    <el-select v-if="item.options" class="w-[40px] mt-[-3px] bg-blue-300" placeholder=""
                      @change="selectChange">
                      <el-option v-for="item in item.options" :label="item.name" :value="item.id" />
                    </el-select>
                    <el-select v-if="item.data.isGroupbyYear == 1" v-model="item.yearValue" multiple collapse-tags
                      collapse-tags-tooltip placeholder="年份选择" class="bg-white mt-[-3px]" style="width: 141px">
                      <el-option v-for="item in yearOptions" :key="item.value" :label="`${item.label}年`"
                        :value="item.value" />
                    </el-select>
                  </span>
                  <!-- <span v-for="(itemSub, indsub) in item" :key="iteindsubmSub" class="bg-blue-400 mx-2 px-2 mb-2 rounded-md text-white">{{itemSub}}</span> -->
                </template>
              </template>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mt-[15px]">
          <div class="flex justify-between">
            <el-form-item label="筛选条件">
              <el-button @click="searchConditionFlag = !searchConditionFlag">
                <span>{{ !searchConditionFlag ? "展开" : "收起" }}</span>
                <el-icon color="#409EFF">
                  <CaretTop v-show="searchConditionFlag" />
                  <CaretBottom v-show="!searchConditionFlag" />
                </el-icon>
              </el-button>
              <el-button @click="clearCondition">清空</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="danger" @click="searchHandler">
                <el-icon color="#fff" :size="19" class="mr-1">
                  <Search />
                </el-icon>
                <span class="text-xs">查询</span>
              </el-button>
              <el-button type="warning" @click="reset">
                <el-icon color="#fff" :size="19" class="mr-1">
                  <Refresh />
                </el-icon>
                <span class="text-xs">重置</span>
              </el-button>
              <!-- <el-button type="success"><el-icon color="#fff" :size="19" class="mr-1">
                  <CircleCheck />
                </el-icon>
                <span class="text-xs">保存配置</span>
              </el-button> -->
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-form-item label=" " v-show="searchConditionFlag">
        <el-row>
          <el-col :span="24">
            <el-form-item v-for="(item, index) in conditions" :label="item.name" label-width="136px" :key="index">
              <el-select v-if="item.type == 'select'" v-model="item.value" placeholder="请选择" class="w-[141px]">
                <el-option v-for="ele in item.options" :label="ele.name || ele.label" :value="ele.name || ele.label"
                  :key="ele.name" />
              </el-select>
              <el-input v-else v-model="item.value" style="width: 141px" placeholder="请输入" />
              <template v-if="item.date">
                <el-date-picker v-model="item.dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
                  start-placeholder="开始日期" end-placeholder="结束日期" style="width: 241px" @change="dateChange" />

                <!-- <el-date-picker
                  v-model="item.beginYear"
                  type="date"
                  placeholder="起始年份" @change="dateChange"
                />
                <el-date-picker
                  v-model="item.endYear"
                  type="date"
                  placeholder="结束年份" @change="dateChange"
                /> -->
              </template>
              <!-- <el-select v-model="searchForm.sex" placeholder="请选择" class="w-[241px]" >
                <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select> -->
              <span>
                <el-icon color="#409EFF" :size="26" class="ml-2" @click="addCondition(item, index)">
                  <CirclePlusFilled />
                </el-icon>
                <el-icon color="rgb(177.3, 179.4, 183.6)" :size="26" class="ml-2" @click="removeCondition(index)">
                  <RemoveFilled />
                </el-icon>
              </span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-card>

  <el-card class="w-full pt-[5px] mt-[10px] min-h-[140px]" v-loading="loading" element-loading-text="数据加载中...">
    <div v-if="tableData.length > 0" class="mb-[20px] text-right">
      <el-button type="primary">
        <el-icon :size="20">
          <Download />
        </el-icon>
        <span class="text-xs">导出</span>
      </el-button>
    </div>
    <!-- 表头设置后，因为计算量不渲染 -->
    <el-table v-if="tableData.length > 0" :data="tableData" class="min-[300px]">
      <el-table-column v-if="tableData.length > 0" type="index" label="序号" width="50" align="center" />
      <template v-for="(item, ind) in tableColumn">
        <el-table-column v-if="!item.childFlag" :key="ind" :label="item.label" :prop="item.Field" align="center"
          :show-overflow-tooltip="true" />
        <template v-else>
          <el-table-column :key="ind" :label="item.label" :prop="item.Field" align="center"
            :show-overflow-tooltip="true">
            <el-table-column v-for="(second, ind2) in item.children" :key="`${ind}-${ind2}`" :label="second.label"
              :prop="second.Field" align="center" :show-overflow-tooltip="true">
              <template v-if="second.childFlag">
                <el-table-column v-for="(third, ind3) in second.children" :key="`${ind}-${ind2}-${ind3}`"
                  :label="third.label" :prop="third.Field" align="center" :show-overflow-tooltip="true" />
              </template>
            </el-table-column>
          </el-table-column>
        </template>
      </template>
    </el-table>
    <div v-if="tableData.length == 0" class="min-h-[140px] flex flex-col justify-center text-center text-gray-400">
      暂无数据！
    </div>
    <!-- <div class="mt-[20px] flex justify-end">       -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    <!-- </div> -->
  </el-card>
</template>
<!-- 检索条件以已选中项目为一项 -->
<script setup>
import { reactive, watch } from "vue"
import useAppStore from '@/store/modules/app'
import { zdyApi, getCategorys } from "@/api/statistics/index.js"
import { yearOptions, options } from "./index.js"
const { proxy } = getCurrentInstance();

// const router = useRouter();
// const appStore = useAppStore()

let dynamicData = {} //模拟数据
const rowProps = {
  label: 'name',
  value: 'id',
  children: 'children',
}
const colProps = {
  multiple: true,
  emitPath: false,
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
}

const searchConditionFlag = ref(false);
const loading = ref(false);
const rowRef = ref()
const colRef = ref()
const rowVal = ref([])
const colVal = ref({})
const rowOptions = ref([])
const colOptions = ref([])
const rowSelected = ref([])
const colSelected = ref([])
const conditions = ref([])
const tableColumn = ref([]);
const tableData = ref([]);
const total = ref(0);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
});


const searchHandler = () => {
  console.log(conditions.value)
}

const rowChange = (val) => {
  reset()
  rowSelected.value = rowRef.value.getCheckedNodes()
  // console.log("rowSelected:",rowSelected.value)
  getColOptions(rowSelected.value[0].data.columnTYPE)
  // conditions.value = []
  // searchConditionFlag.value = false
  // colVal.value = []
}

const colChange = (val) => {
  const curr = []
  loading.value = true;
  console.log("col变化时触发的事件--------------", curr, val, colVal.value)
  if (val.length > 5) {
    proxy.$modal.msgWarning("最大可选5个选项")
    val.splice(5);

    colVal.value = []  // 选中项变化，只有清空选中项的值，再重新设置选中项才会触发渲染，否则 
    setTimeout(() => {
      colVal.value = val
      // console.log(colRef.value.getCheckedNodes(),val, colVal.value)
    }, 10)

    loading.value = false;
    return
  }

  let columns = []
  // 生成行表头
  columns.push({
    id: 1,
    label: rowSelected.value[0].label,
    Field: rowSelected.value[0].data.nameLocal,
    childFlag: false
  })
  dynamicData[rowSelected.value[0].data.nameLocal] = rowSelected.value[0].label

  colSelected.value = colRef.value.getCheckedNodes()
  console.log("colSelected:", colSelected.value)
  colSelected.value.forEach(async (item, index) => {
    const ind = index + 2
    if (item.children.length === 0) { // 过滤掉父级项目 children.length>0， 则不是最终节点，需要过滤掉
      // 生成列表头
      let childObj = {
        id: ind,
        label: item.label,
        Field: item.data.nameLocal,
        childFlag: false
      }
      dynamicData[item.data.nameLocal] = item.label + "-1"

      //列表头选包含下拉选项
      if (item.data.bizName) {
        const res = await getCategorys({ bizName: item.data.bizName })
        if (res.code === 200) {
          item.options = res.data
          // 列表头 二级
          childObj.childFlag = res.data && res.data.length > 0 ? true : false
          if (childObj.childFlag) {
            let children = []
            res.data.forEach((child, subIndex) => {
              const currField = item.data.nameLocal + child.code
              let obj = {
                label: child.name,
                id: currField,
                Field: currField, // 没有该字段时 ，拼接唯一字段
                childFlag: false
              }
              dynamicData[currField] = child.name
              // 年选项处理为 三级标题（或者和二级标题呼唤等级）
              if (item.data.isGroupbyYear == 1) {
                console.log("三级---------------------------")
                obj.childFlag = true
                const currYear = new Date().getFullYear()
                let arr = []
                for (let i = 0; i < 5; i++) {
                  arr.push({
                    id: currYear - i,
                    label: `${currYear - i}年`,
                    Field: currYear - i,
                    childFlag: false
                  })
                  dynamicData[currYear - i] = `${currYear - i}年`
                }
                obj.children = arr
              }
              children.push(obj)
            })
            childObj.children = children
          }
        }
      } else if (item.data.isGroupbyYear === 1) {
        // item.yearValue = ''
        const currYear = new Date().getFullYear()
        childObj.children = []
        for (let i = 0; i < 5; i++) {
          childObj.children.push({
            id: currYear - i,
            label: `${currYear - i}年`,
            Field: currYear - i,
            childFlag: false
          })
          dynamicData[currYear - i] = `${currYear - i}年`
        }
      }
      // 生成列表头
      columns.push(childObj)
      tableColumn.value = columns


      // 检索条件
      // if(item.children.length===0){
      const index = conditions.value.findIndex((x) => x.name === item.label)
      if (index === -1) {
        let obj = {
          name: item.label,
          value: "",
          type: "input"
        }
        if (item.options && item.options.length > 0) {
          obj.type = "select"
          obj.options = item.options
        }
        if (item.data.isGroupbyYear == 1) {
          obj.date = true
        }
        conditions.value.push({
          ...obj
        })
      }
      // }
    }

  })

  setTimeout(() => {
    // tableData.value = []
    tableData.value = [dynamicData, dynamicData, dynamicData]
    total.value = 3
    loading.value = false;
  }, 1000);

  // console.log("conditions:",conditions.value)
  // console.log("colSelected:",colSelected.value)
  // console.log("columns:",columns)
}
const removeCondition = (index) => {
  //  数据重新组装，根据下标删除
  // const index = conditions.value.findIndex((x) => x.value === item.value)
  conditions.value.splice(index, 1)
}
const addCondition = (item, ind) => {
  let obj = {
    name: item.name,
    value: "",
    type: "input"
  }
  if (item.options && item.options.length > 0) {
    obj.type = "select"
    obj.options = item.options
  }
  if (item.date) {
    obj.date = true
  }
  conditions.value.splice(ind + 1, 0, obj)
}

//
const dateChange = (param) => {
  console.log(param, conditions.value)
};
const selectChange = (param) => {
  console.log(param)
};

const clearCondition = () => {
  conditions.value = []
};
const reset = () => {
  colOptions.value = []
  rowSelected.value = []
  colSelected.value = []
  tableColumn.value = []
  tableData.value = []
  rowVal.value = []
  colVal.value = []
  total.value = 0
  conditions.value = []
  searchConditionFlag.value = false
  // history.go(0)
  // location.reload()
};
const digui = (data) => {
  data.forEach((item) => {
    if (item.name == rowSelected.value[0].label) {
      item.disabled = true
    } else if (item.children && item.children.length > 0) {

      digui(item.children)
    }
  })
}
const getRowOptions = async () => {
  const res = await zdyApi.getCustomstats()
  console.log(res)
  if (res.code == 200) {
    rowOptions.value = res.data
    console.log(rowOptions.value)
  }
}
const getColOptions = async (columnTYPE) => {
  colSelected.value = []
  const res = await zdyApi.fiveYHonorStats({ columnTYPE: columnTYPE })
  console.log(res)
  if (res.code == 200) {
    res.data.forEach((item, ind) => {
      if (item.label == rowSelected.value[0].label) {
        item.disabled = true
      } else if (item.children && item.children.length > 0) {
        item.disabled = true
        digui(item.children)
      }
    })
    colOptions.value = res.data
  }
}
const setItem = (item) => {
  let str = ''
  for (let i = 0; i < item.length; i++) {

    if (i == 0) {
      str += item[i]
    } else {
      str += "/" + item[i]
    }
  }
  return str
}
getRowOptions()
</script>

<style scoped lang="scss">
.block-title {
  color: #454545;
  // border-left: 7px solid #409EFF;
  // padding-left: 12px;
  height: 36px;
  display: block;
  line-height: 36px;

  .des-title {
    font-size: 14px;
    font-weight: 400;
    color: #b4b6bb;
  }
}

.line-view {
  width: 1920px;
  height: 6px;
  background: #3787FF;
  box-shadow: 0px 5px 20px 0px rgba(0, 0, 0, 0.47);
  opacity: 0.24;
}

// 重构级联样式
::v-deep .el-form-item__content {
  align-items: start;
  flex-wrap: nowrap;
}

::v-deep .el-cascader__tags {
  height: 30px;
  overflow: hidden;
  display: none;
}

::v-deep .el-input__wrapper {
  background-color: transparent;
}

::v-deep .el-cascader .el-input {
  width: 214px;
}

::v-deep .el-cascader .el-input .el-input__inner {
  color: transparent;
}

::v-deep .el-checkbox.is-disabled {
  cursor: not-allowed;
  display: none !important;
}

::v-deep .el-checkbox__input.is-disabled .el-checkbox__inner {
  cursor: not-allowed;
  display: none !important;
}
</style>
<style>
.se-box .el-checkbox.is-disabled {
  cursor: not-allowed;
  display: none !important;
}
</style>
